//
//  NearbyFriendsViewController.m
//  GolfFriend
//
//  Created by vescky on 13-12-16.
//  Copyright (c) 2013年 vescky.org. All rights reserved.
//

#import "NearbyFriendsViewController.h"
#import "NearbyFriendsCell.h"
#import "CommonUtility.h"
#import "AppsLocationManager.h"
#import "AppsEngine.h"
#import "JSON.h"
#import "MJRefresh.h"
#import "UserSession.h"
#import "GFVOParser.h"
#import "UserPublicInfoVO.h"
#import "PersonalInfoViewController.h"

@interface NearbyFriendsViewController () <UITableViewDataSource,UITableViewDelegate,MJRefreshBaseViewDelegate,UIActionSheetDelegate> {
    int currentPage;
    NSMutableArray *nfArray;
    
    //下拉刷新，上拉加载更多
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    
    UIActionSheet *filterAs;
    NSString *showSex;
}

@end

@implementation NearbyFriendsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.navigationController.navigationBar setHidden:NO];
    [self setTitle:@"附近名媛"];
    [super customBackButton];
    [super customNavigationBarRightButtonWithTitleName:@"筛选"];
    [self initData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Private
- (void)initData {
    currentPage = 1;
    NSString *cacheString = [[UserSession shareUserSession] getNearbyUserList];
    if (cacheString && cacheString.length > 0) {
        nfArray = [[NSMutableArray alloc] initWithArray:[cacheString JSONValue]];
    }
    
    if (!nfArray) {
        nfArray = [[NSMutableArray alloc] init];
    }
    
    if ([[UserSession shareUserSession] getDefaultNearbyProperty]) {
        showSex = [[UserSession shareUserSession] getDefaultNearbyProperty];
    }
    else {
        showSex = @"all";
    }
    
    [self getDataFromServer];

}


- (void)getDataFromServer {
    CLLocation *currentLocation = [[AppsLocationManager sharedManager] currentLocation];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                 [NSString stringWithFormat:@"%d",currentPage],@"page",
                                 [[UserSession shareUserSession] getUserId],@"userId",
                                 [NSString stringWithFormat:@"%lf",currentLocation.coordinate.latitude],@"latitude",
                                 [NSString stringWithFormat:@"%lf",currentLocation.coordinate.longitude],@"longitude",nil];
    if (showSex && showSex.length > 0) {
        [dict setObject:showSex forKey:@"sex"];
    }
    
    [[AppsEngine shareAppsEngine] submitRequest:@"gfGetNearUserList" param:dict onCompletion:^(id jsonResponse) {
        NSMutableArray *fList = [jsonResponse objectForKey:@"list"];
        if (fList && [fList respondsToSelector:@selector(count)]) {
            if (currentPage <= 1) {
                [[UserSession shareUserSession] saveNearbyList:[fList JSONFragment]];
                currentPage++;
                [nfArray removeAllObjects];
            }
            [nfArray addObjectsFromArray:fList];
            nfArray = [self resortArray:nfArray];
            [tbView reloadData];
        }
    } onError:^(NSError *error) {
        NSLog(@"获取数据失败");
    } method:@"GET"];
}


- (void)initView {
    //初始化刷新view
    _header = [MJRefreshHeaderView header];
    _header.scrollView = nfScrollView;
    _header.delegate = self;
    
    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.scrollView = nfScrollView;
    _footer.delegate = self;
    
}


- (NSMutableArray*)resortArray:(NSMutableArray*)_arr {
    if (!_arr || [_arr count] < 1) {
        return nil;
    }
    _arr = [self removeSameItemInArray:_arr];
    
    //位置远近
    NSArray *sortedArr = [_arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
//        NSString *locationString1 = [NSString stringWithFormat:@"%@,%@",[obj1 objectForKey:@"lastLoginLongitude"],[obj1 objectForKey:@"lastLoginLatitude"]];
//        NSString *locationString2 = [NSString stringWithFormat:@"%@,%@",[obj2 objectForKey:@"lastLoginLongitude"],[obj2 objectForKey:@"lastLoginLatitude"]];
//        CLLocation *location1 = getGfLocation(locationString1);
//        CLLocation *location2 = getGfLocation(locationString2);
//        double distan1 = [[AppsLocationManager sharedManager] getDistance:location1];
//        double distan2 = [[AppsLocationManager sharedManager] getDistance:location2];
        
        double distan1 = [[obj1 objectForKey:@"distance"] doubleValue];
        double distan2 = [[obj2 objectForKey:@"distance"] doubleValue];
        
        if (distan1 > distan2) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        else {
            return (NSComparisonResult)NSOrderedAscending;
        }
        
        return (NSComparisonResult)NSOrderedSame;
    }];
    
    return [[NSMutableArray alloc] initWithArray:sortedArr];
}

- (NSMutableArray*)removeSameItemInArray:(NSMutableArray*)_arr {
    NSMutableDictionary *rDict = [[NSMutableDictionary alloc] init];
    for (int i = 0; i < [_arr count]; i++) {
        NSDictionary *_dict = [_arr objectAtIndex:i];
        [rDict setObject:_dict forKey:[_dict objectForKey:@"uId"]];
    }
    
    NSMutableArray *rArr = [[NSMutableArray alloc] init];
    NSEnumerator *_enum = [rDict keyEnumerator];
    for (NSString *key in _enum) {
        [rArr addObject:[rDict objectForKey:key]];
    }
    return rArr;
}


#pragma mark - 刷新的代理方法---进入下拉刷新\上拉加载更多都有可能调用这个方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    if (refreshView == _header) {
        // 下拉刷新
        
    }
    else {
        //上拉加载更多
        
    }
    
    [self getDataFromServer];
}


#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [nfArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"NearbyFriendsCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell){
        cell = [[[NSBundle mainBundle] loadNibNamed:@"NearbyFriendsCell" owner:self options:nil] objectAtIndex:0];
    }
    
    if([cell respondsToSelector:@selector(setDataInfo:)]){
        [cell performSelector:@selector(setDataInfo:) withObject:[nfArray objectAtIndex:indexPath.row]];
    }
    
    [cell setTag:indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tbView deselectRowAtIndexPath:indexPath animated:YES];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:[nfArray objectAtIndex:indexPath.row]];
    [dict setObject:[dict objectForKey:@"uId"] forKey:@"userId"];
    [dict removeObjectForKey:@"uId"];
    [dict setObject:[dict objectForKey:@"id"] forKey:@"recordId"];
    [dict removeObjectForKey:@"id"];
//    UserPublicInfoVO *upInfo = [[GFVOParser shareParser] parseDataForUserPublicInfo:dict];
//    NSMutableDictionary *upDict = [[NSMutableDictionary alloc] initWithDictionary:[upInfo toDictionary]];
    PersonalInfoViewController *picv = [[PersonalInfoViewController alloc] init];
    picv.userInfo = dict;
    [self.navigationController pushViewController:picv animated:YES];
}

#pragma mark - Overwrite methor
- (void)rightBarButtonAction {
    NSLog(@"need to implement this methor");
    if (!filterAs) {
        filterAs = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"显示全部",@"只显示男",@"只显示女", nil];
    }
    [filterAs showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        //显示全部
        showSex = @"all";
    }
    else if (buttonIndex == 1) {
        //显示男
        showSex = @"male";
    }
    else if (buttonIndex == 2) {
        //显示女
        showSex = @"female";
    }
    currentPage = 1;
    [self getDataFromServer];
    [[UserSession shareUserSession] saveDefaultNearbyProperty:showSex];
}


@end
